#!/bin/bash

# Java 测试运行脚本
# 使用方法: ./run_test.sh

set -e

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# 检查 Java 是否安装
if ! command -v javac &> /dev/null; then
    echo "错误: 未找到 javac 命令"
    echo "请先安装 Java JDK:"
    echo "  macOS: brew install openjdk"
    echo "  Linux: sudo apt-get install openjdk-11-jdk"
    exit 1
fi

if ! command -v java &> /dev/null; then
    echo "错误: 未找到 java 命令"
    echo "请先安装 Java JDK"
    exit 1
fi

echo "Java 版本:"
java -version
echo ""

# 检查动态库是否存在
DYLIB_PATH="$PROJECT_ROOT/target/release/libqa_ffi.dylib"
SO_PATH="$PROJECT_ROOT/target/release/libqa_ffi.so"

if [ ! -f "$DYLIB_PATH" ] && [ ! -f "$SO_PATH" ]; then
    echo "错误: 未找到动态库文件"
    echo "请先编译 Rust 代码:"
    echo "  cd $PROJECT_ROOT && cargo build --release"
    exit 1
fi

# 确定动态库路径
if [ -f "$DYLIB_PATH" ]; then
    LIB_PATH="$PROJECT_ROOT/target/release"
    echo "找到动态库: $DYLIB_PATH"
elif [ -f "$SO_PATH" ]; then
    LIB_PATH="$PROJECT_ROOT/target/release"
    echo "找到动态库: $SO_PATH"
fi

# 编译 Java 代码
echo ""
echo "编译 Java 代码..."
cd "$SCRIPT_DIR"
javac -d . *.java

if [ $? -ne 0 ]; then
    echo "错误: Java 编译失败"
    exit 1
fi

echo "编译成功！"
echo ""

# 运行测试
echo "运行测试..."
echo "=========================================="
java -Djava.library.path="$LIB_PATH" Example
echo "=========================================="
echo ""
echo "测试完成！"


